package com.wjh.rules.assembler.operator.chain.unit;

import com.wjh.rules.assembler.operator.chain.AbstractOperator;
import com.wjh.rules.common.conts.OperatorConts;
import com.wjh.rules.common.conts.ScriptOpetorConts;

import java.nio.file.OpenOption;

public class LikeOperator extends AbstractOperator {
    public LikeOperator(String type) {
        super(type);
    }

    /**
     * column like %111%
     *
     * @param message
     * @return
     * @throws Exception
     */
    @Override
    protected String format(String message) throws Exception {

        message = this.templateSimpleParam(message);
        String[] arr = message.split(this.operatorType);
        String left = arr[0].trim();
        String right = arr[1].trim();
        boolean startsWith = right.startsWith("%");
        boolean endsWith = right.endsWith("%");
        StringBuffer sb = new StringBuffer();
        if (startsWith && endsWith) {
            right = right.substring(1, right.length() - 1);
            sb.append(left);
            sb.append(ScriptOpetorConts.SCRIPT_INDEX_OF).append(ScriptOpetorConts.SCRIPT_LEFT_BRACKETS);
            sb.append(right);
            sb.append(ScriptOpetorConts.SCRIPT_RIGHT_BRACKETS);
            sb.append(ScriptOpetorConts.SCRIPT_BLANK).append(ScriptOpetorConts.SCRIPT_CONTAINS);
        } else if (startsWith && !endsWith) {
            String substring = right.substring(1);
            sb.append(left)
                    .append(".startsWith(")
                    .append(substring)
                    .append(")");
        } else if (!startsWith && endsWith) {
            String substring = right.substring(0, right.length() - 1);
            sb.append(left)
                    .append(".endsWith(")
                    .append(substring)
                    .append(")");
        } else {
            String replace = message.replace(this.operatorType, OperatorConts.EQUAL);
            return replace;
        }
        return sb.toString();
    }
}
